import 'package:flutter/material.dart';
import 'package:flutter_module/beans/data_layer_item_selection_bean.dart';
import 'package:flutter_module/viewModels/layer_edit_viewmodel.dart';
import 'package:provider/provider.dart';

class SingleSelection extends StatefulWidget {
  const SingleSelection({Key? key}) : super(key: key);

  @override
  State<SingleSelection> createState() => _SingleSelectionState();
}

class _SingleSelectionState extends State<SingleSelection> {
  late final LayerEditViewModel _model =
      Provider.of<LayerEditViewModel>(context, listen: false);

  final Map<SelectionBean, List<TextEditingController>> _controllerMap = {};
  final _listKey = GlobalKey<AnimatedListState>();

  @override
  void initState() {
    super.initState();
  }

  @override
  void didChangeDependencies() {
    if (_model.curItem.selectOptions != null) {
      _model.initSingleSelectionItem(list: _model.curItem.selectOptions);
    } else {
      _model.initSingleSelectionItem();
    }

    if (_model.selectionList.isEmpty) {
      var v1 = SelectionBean("选项一", "0");
      var v2 = SelectionBean("选项二", "1");
      _model.selectionList.add(v1);
      _model.selectionList.add(v2);
      TextEditingController c11 = TextEditingController();
      c11.text = v1.name;
      c11.addListener(() {
        v1.name = c11.text;
      });
      TextEditingController c12 = TextEditingController();
      c12.text = v1.value;
      c12.addListener(() {
        v1.value = c12.text;
      });
      TextEditingController c21 = TextEditingController();
      c21.text = v2.name;
      c21.addListener(() {
        v2.name = c21.text;
      });
      TextEditingController c22 = TextEditingController();
      c22.text = v2.value;
      c22.addListener(() {
        v2.value = c22.text;
      });
      _controllerMap.putIfAbsent(v1, () => [c11, c12]);
      _controllerMap.putIfAbsent(v2, () => [c21, c22]);
    } else {
      for (var item in _model.curItem.selectOptions!) {
        TextEditingController c11 = TextEditingController();
        c11.text = item.name;
        c11.addListener(() {
          item.name = c11.text;
        });
        TextEditingController c12 = TextEditingController();
        c12.text = item.value;
        c12.addListener(() {
          item.value = c12.text;
        });
        _controllerMap.putIfAbsent(item, () => [c11, c12]);
      }
    }
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    for (var element in _controllerMap.values) {
      element[0].dispose();
      element[1].dispose();
      element.clear();
    }
    _controllerMap.clear();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        IconButton(
            onPressed: () {
              var selectionBean = SelectionBean("", "");
              _model.selectionList.add(selectionBean);
              TextEditingController c1 = TextEditingController();
              c1.addListener(() {
                selectionBean.name = c1.text;
              });
              TextEditingController c2 = TextEditingController();
              c2.addListener(() {
                selectionBean.value = c2.text;
              });
              _controllerMap.putIfAbsent(selectionBean, () => [c1, c2]);
              _listKey.currentState!
                  .insertItem(_model.selectionList.length - 1);
            },
            icon: const Icon(Icons.add_circle_outline_rounded)),
        AnimatedList(
          shrinkWrap: true,
          //为true可以解决子控件必须设置高度的问题
          physics: const NeverScrollableScrollPhysics(),
          key: _listKey,
          initialItemCount: _model.selectionList.length,
          itemBuilder: (context, index, animation) {
            return _itemWidget(index, animation, false);
          },
        ),
      ],
    );
  }

  Widget _itemWidget(int index, Animation<double> scale, bool isRemove) {
    return ScaleTransition(
      scale: scale,
      child: Padding(
        padding: const EdgeInsets.only(left: 20, right: 20),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: isRemove
                        ? null
                        : _controllerMap[_model.selectionList[index]]![0],
                    decoration: InputDecoration(
                      labelText: '选择项名称: ',
                      hintText: "请输入选项项名称",
                      labelStyle: const TextStyle(color: Colors.red),
                      icon: const Icon(Icons.insert_drive_file),
                      suffixIcon: IconButton(
                        tooltip: '清空',
                        icon: const Icon(Icons.clear),
                        onPressed: () {
                          if (!isRemove) {
                            _controllerMap[_model.selectionList[index]]![0]
                                .text = "";
                          }
                        },
                      ),
                    ),
                  ),
                ),
                IconButton(
                  onPressed: () {
                    if (!isRemove) {
                      var item = _model.selectionList.removeAt(index);
                      _listKey.currentState!.removeItem(
                        index,
                        (context, animation) => _itemWidget(index, scale, true),
                      );
                      Future.delayed(const Duration(milliseconds: 400))
                          .then((value) {
                        _controllerMap[item]?[0].dispose();
                        _controllerMap[item]?[1].dispose();
                        _controllerMap.remove(item);
                      });
                    }
                  },
                  icon: const Icon(Icons.remove_circle_outline_outlined),
                ),
              ],
            ),
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: isRemove
                        ? null
                        : _controllerMap[_model.selectionList[index]]![1],
                    decoration: InputDecoration(
                      labelText: '选择项隐藏值: ',
                      hintText: "请输入选择项隐藏值",
                      labelStyle: const TextStyle(color: Colors.red),
                      icon: const Icon(Icons.insert_drive_file),
                      suffixIcon: IconButton(
                        tooltip: '清空',
                        icon: const Icon(Icons.clear),
                        onPressed: () {
                          if (!isRemove) {
                            _controllerMap[_model.selectionList[index]]![1]
                                .text = "";
                          }
                        },
                      ),
                    ),
                  ),
                ),
                IconButton(
                  onPressed: () {
                    if (!isRemove) {
                      _controllerMap[_model.selectionList[index]]![1].text =
                          _controllerMap[_model.selectionList[index]]![0].text;
                    }
                  },
                  icon: const Icon(Icons.copy_outlined),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}
